<template>
  <div>
    <form @submit.prevent="submitForm">
      <!-- 周次复选框 -->
      <div class="form-row">
        <label>周次:</label>
        <div v-for="n in 20" :key="n" class="form-checkbox">
          <input type="checkbox" :id="'week-' + n" :value="n" v-model="selectedWeeks">
          <label :for="'week-' + n">{{ n }}</label>
        </div>
      </div>
      
      <!-- 实验室复选框 -->
      <div class="form-row">
        <label>实验室:</label>
        <div class="lab-checkbox-container">
          <div v-for="n in 22" :key="n" class="form-checkbox">
            <input type="checkbox" :id="'lab-' + (n + 900)" :value="(n + 900)" v-model="selectedLabs">
            <label :for="'lab-' + (n + 900)">{{ (n + 900) }}</label>
          </div>
        </div>
      </div>
      
      <!-- 课程下拉框 -->
      <div class="form-row">
        <label>课程:</label>
        <select v-model="selectedCourse">
          <option value="" disabled>请选择课程</option>
          <option v-for="course in courses" :key="course.id" :value="course.id">{{ course.name }}</option>
        </select>
      </div>
      
      <!-- 表格 -->
      <table class="schedule-table">
        <thead>
          <tr>
            <th>时间/日期</th>
            <th v-for="day in days" :key="day">{{ day }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="time in times" :key="time">
            <th>{{ time }}节</th>
            <td v-for="day in days" :key="day" @mouseover="hoverCell(day, time)" @click="showInfo(day, time)">
              <!-- 只显示“有课”或者不显示 -->
              <span v-if="getAppointment(day, time)">{{ '有课' }}</span>
            </td>
          </tr>
        </tbody>
      </table>
    </form>
    
    <!-- 弹窗 -->
    <div v-if="selectedCell" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <p>课程名称: {{ selectedCell.courseName }}</p>
        <p>教师: {{ selectedCell.teacherName }}</p>
        <p>地点: {{ selectedCell.labName }}</p>
        <p>周次: {{ selectedCell.weekRange }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'InquireClassSchedule',
  data() {
    return {
      selectedWeeks: [],
      selectedLabs: [],
      selectedCourse: '',
      courses: [],
      days: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      times: ['1、2', '3、4', '5、6', '7、8', '9、10', '11、12'],
      selectedCell: null,
      hoverDay: null,
      hoverTime: null,
      scheduleData: []
    };
  },
  created() {
    this.fetchCourses();
  },
  watch: {
    selectedWeeks(newVal) {
      this.sendDataToBackend();
    },
    selectedLabs(newVal) {
      this.sendDataToBackend();
    },
    selectedCourse(newVal) {
      this.sendDataToBackend();
    }
  },
  methods: {
    async fetchCourses() {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('http://192.168.129.76:8080/api/courses', {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        this.courses = response.data.data;
      } catch (error) {
        console.error('获取课程信息错误:', error);
        if (error.response && error.response.status !== 200) {
          alert('Token无效或已过期，请重新登录。');
        } else {
          alert('获取课程信息失败，请检查网络连接。');
        }
      }
    },
    async sendDataToBackend() {
      try {
        const token = localStorage.getItem('token');
        const requestData = {
          weeks: this.selectedWeeks,
          labs: this.selectedLabs,
          course: this.selectedCourse
        };
        const response = await axios.post('http://192.168.129.76:8080/api/appointment_json', requestData, {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        // 处理响应数据
        this.scheduleData = this.mergeWeeks(response.data.data);
        console.log(this.scheduleData);
      } catch (error) {
        console.error('发送数据到后端错误:', error);
        if (error.response && error.response.status !== 200) {
          alert('Token无效或已过期，请重新登录。');
        } else {
          alert('发送数据失败，请检查网络连接。');
        }
      }
    },
    hoverCell(day, time) {
      this.hoverDay = day;
      this.hoverTime = time;
    },
    showInfo(day, time) {
      const cellInfo = this.scheduleData.find(item => item.dayofweek === this.days.indexOf(day) && item.section === this.times.indexOf(time) + 1);
      if (cellInfo) {
        this.selectedCell = cellInfo;
      } else {
        this.selectedCell = null;
      }
      this.hoverDay = null;
      this.hoverTime = null;
    },
    closeModal() {
      this.selectedCell = null;
    },
    getAppointment(day, time) {
      return this.scheduleData.some(item =>
        item.dayofweek === this.days.indexOf(day) && item.section === this.times.indexOf(time) + 1
      );
    },
    mergeWeeks(data) {
    const groupedData = {};

    // 1. 分组数据
    data.forEach(item => {
      const key = `${item.courseName}-${item.teacherId}-${item.labName}-${item.dayofweek}-${item.section}`;
      if (!groupedData[key]) {
        groupedData[key] = {
          courseName: item.courseName,
          teacherName: item.teacherName,
          labName: item.labName,
          dayofweek: item.dayofweek,
          section: item.section,
          weeks: []
        };
      }
      groupedData[key].weeks.push(item.week);
    });

    // 2. 合并周次
    for (const key in groupedData) {
      const weeks = groupedData[key].weeks;
      const sortedWeeks = weeks.sort((a, b) => a - b);
      const startWeek = sortedWeeks[0];
      let endWeek = sortedWeeks[0];

      for (let i = 1; i < sortedWeeks.length; i++) {
        if (sortedWeeks[i] !== endWeek + 1) {
          break;
        }
        endWeek = sortedWeeks[i];
      }

      groupedData[key].weekRange = `${startWeek}-${endWeek}`;
    }

    // 3. 返回处理后的数据
    return Object.values(groupedData);
  },
  },
};
</script>

<style scoped>
.lab-checkbox-container {
  display: grid;
  grid-template-columns: repeat(11, 1fr);
  gap: 10px; /* 调整复选框之间的间距 */
}

.form-checkbox {
  margin-bottom: 10px; /* 调整最后一行复选框的底部间距 */
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px; /* 增加间距 */
  color: #1e4166; /* 设置文本颜色为蓝色 */
}

.form-checkbox {
  margin-right: 10px;
}

.form-row label {
  margin-right: 20px;
  font-weight: bold; /* 加粗标签文本 */
  color: #1a4a7d; /* 设置标签颜色为蓝色 */
}

.schedule-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px; /* 表格与表单之间的间距 */
}

.schedule-table th,
.schedule-table td {
  border: 1px solid #cfe0ff; /* 设置表格边框颜色为蓝色 */
  padding: 8px;
  text-align: center;
}

.schedule-table th {
  background-color: #d8e3f5; /* 设置表头背景颜色为蓝色 */
  color: rgb(127, 139, 192); /* 设置表头文本颜色为白色 */
}

.schedule-table td{
  background-color: #f3f7ff;
}
.schedule-table td:hover {
  background-color: #cce5ff; /* 设置鼠标悬停时的背景颜色 */
}

.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(123, 123, 123, 0.5); /* 设置模态框背景颜色为半透明蓝色 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  border: 1px solid #2f4256; /* 设置模态框边框颜色为蓝色 */
}

.close {
  cursor: pointer;
  float: right;
  color: #1069c7; /* 设置关闭按钮颜色为蓝色 */
}

.close:hover {
  color: #073464; /* 设置关闭按钮悬停时的颜色 */
}
</style>